package com.me.learnspring.controller;

import cn.hutool.core.util.NumberUtil;
import com.me.learnspring.controller.request.NewDrinkRequest;
import com.me.learnspring.model.Drink;
import com.me.learnspring.service.CategoryService;
import com.me.learnspring.service.DrinkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/drink")
public class DrinkController {
	@Autowired
	private DrinkService drinkService;
	
	@Autowired
	private CategoryService categoryService;
	
	@PostMapping(value = "/save", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public Drink createNewDrink(@Valid NewDrinkRequest drinkRequest, BindingResult result) {
		if (result.hasErrors()) {
			log.warn(result.toString());
			return null;
		}
		if (drinkRequest.getCategoryId() != null) {
			return drinkService.saveDrink(drinkRequest);
		}
		return null;
	}
	
	@PostMapping(value = "/save",consumes = MediaType.APPLICATION_JSON_VALUE)
	public Drink createNewDrinkFromJson(@RequestBody NewDrinkRequest drinkRequest){
		if (drinkRequest.getCategoryId() != null) {
			return drinkService.saveDrink(drinkRequest);
		}
		return null;
	}
	
	@PostMapping(value = "/save",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public List<Drink> batchCreateDrink(MultipartFile file){
		List<NewDrinkRequest> drinkRequests = new ArrayList<>();
		
		if (file != null && !file.isEmpty()) {
			BufferedReader reader = null;
			
			try {
				reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
				String line;
				while ((line = reader.readLine()) != null) {
					String[] arr = line.split(",");
					drinkRequests.add(
						new NewDrinkRequest(arr[0],
							Long.parseLong(arr[2]),
							Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(arr[1])))
					);
				}
				
				return drinkService.batchSave(drinkRequests);
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				IOUtils.closeQuietly(reader);
			}
			
		}
		// if (drinkRequest.getCategoryId() != null) {
		// 	return drinkService.saveDrink(drinkRequest);
		// }
		return null;
	}
	
	@GetMapping("/")
	public Page<Drink> getAllByCategoryId(String categoryId,String page,String size){
		return drinkService.getPageByCatgoryId(
			Long.valueOf(categoryId),
			PageRequest.of(Integer.parseInt(page), Integer.parseInt(size))
		);
	}
	
	@GetMapping("")
	public String getByCategory(String category, Model model) {
		List<Drink> drinks = drinkService.getByCatgoryId(Long.valueOf(category));
		model.addAttribute("drinks", drinks);
		model.addAttribute("category", categoryService.findById(Long.valueOf(category)));
		return "drink/drinks";
	}
	
}
